How to select first row in each GROUP BY group?
How to select first row in each GROUP BY group?
254
15-Jul-2024
Updated on 15-Jul-2024
Ashutosh Kumar Verma
15-Jul-2024In SQL Server, you can use the
ROW_NUMBER()function with a Common Table Expression (CTE) or subquery to achieve this,Suppose we have two SQL table,
Departments Table
Employees Table
Let's see the processed,
By using SQL, server Subquery you can easily select the first records from each grouped items.
Example-
Output-
Using SQL CTE
You can also achieve the same result by using the SQL CTE (Common Table Expression)
Example-
Output-
In the example above-
ROW_NUMBER()This function assigns a unique sequence of integers to each row in the partition of the result set defined by thePARTITION BYclause. The ORDER BY clause inROW_NUMBER()determines the order in which the numbers are assigned.PARTITION BYSpecifies how to divide the result set into partitions. Rows with the same values in YourGroupColumn will belong to the same partition.ORDER BYDefines the order of the rows in each partition. SomeColumn is often used here to refer to the first row.If you apply condition
RowNum = 1, you are effectively selecting only the first row in each group defined byD.Namecolumn.Also, Read: How to concatenate text from multiple rows into a single text string in SQL Server